package com.raptor.trustworthy.server.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.raptor.trustworthy.server.dao.GoDao;
import com.raptor.trustworthy.server.model.Result;
import com.raptor.trustworthy.server.properties.UploadProperties;
import com.raptor.trustworthy.server.service.ReadAndUpload;
import com.raptor.trustworthycore.util.BeanUtil;
import com.raptor.trustworthycore.util.DateUtil;
import com.raptor.trustworthycore.util.ListsUtil;
import com.raptor.trustworthycore.util.RandomUtil;
import com.raptor.trustworthycore.util.SftpUtil;
import com.raptor.trustworthycore.util.StringUtil;
import com.raptor.trustworthycore.util.UploadUtil;
import com.raptor.trustworthypojo.pojo.CookUploadLog;
import com.raptor.trustworthypojo.pojo.TCooker;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author renhuan
 * @Date 2021-05-14 17:24
 **/
@Service
public class ReadAndUploadImpl implements ReadAndUpload {

  @Autowired
  private GoDao goDao;

  @Autowired
  private UploadProperties uploadProperties;

  @Override
  public List<TCooker> readCooker() {

    return null;
  }

  @Override
  public String uploadCooker(List<TCooker> cookers) {

    Result result = new Result();
    result.setResultCode("0");
    result.setResultMsg("上传成功");

    //获取本地暂存位置
    String resourcePath = this.getClass().getResource("/").getPath();
    String localFilePath = resourcePath + uploadProperties.getLocalFilePath();
    Date nowTime = new Date();
    //txt文件名
    String fileName =
        "cook" + DateUtil.getFormatTimeString(nowTime, DateUtil.DATE_FORMATE_STRING_K) + ".txt";
    //压缩zip文件名
    String zipName =
        "cook" + DateUtil.getFormatTimeString(nowTime, DateUtil.DATE_FORMATE_STRING_K) + ".txt";
    //上传批次
    String upLoadNo = DateUtil.getFormatTimeString(new Date(), DateUtil.DATE_FORMATE_STRING_K);
    try {
      //查询上传日志表，如果已经有本批次上传成功记录，不再上传
      if (checkUploadCooker(upLoadNo)) {
        result.setResultCode("0");
        result.setResultMsg("have be upload before");
        return JSONObject.toJSONString(result);
      }
      //检查临时地址是否存在,不存在逐级创建
      UploadUtil.judeDirExists(localFilePath);

      //查询数据
      List<TCooker> TCookers = goDao.queryAllCook();
      List<Map<String, Object>> tCookersMap = new ArrayList<>();
      for (TCooker tCooker : TCookers){
        Map<String, Object> tCookerMap =  BeanUtil.beanToMap(tCooker);
        tCookersMap.add(tCookerMap);
      }

      //写txt文件
      UploadUtil.writeTxt(tCookersMap, fileName, localFilePath);

      //压缩
      UploadUtil.compressTxt(localFilePath, fileName, zipName);

      //上传
      String hostname = uploadProperties.getUploadSftpHomeName();
      int port = uploadProperties.getUploadSftpPort();
      String username = uploadProperties.getUploadSftpUserinfo();
      String password = uploadProperties.getUploadSftpPassword();
      String remotePath = uploadProperties.getRemotePath();
      if (remotePath != null && !remotePath.endsWith("/")) {
        remotePath = remotePath + "/";
      }
      String realRemotePath =
          remotePath + DateUtil.getBeforeHourString(1, DateUtil.DATE_FORMATE_STRING_H);
      SftpUtil sftp = new SftpUtil(hostname, port, username, password);
      if (fileName != null && !"".equals(fileName)) {
        String eStr = "";
        eStr = sftp.connect();
        if (!"true".equals(eStr)) {
          sftp.disconnect();
          throw new Exception(eStr);
        }
        eStr = sftp.upload(realRemotePath, localFilePath + zipName);
        sftp.disconnect();
        if (!"true".equals(eStr)) {
          throw new Exception(eStr);
        }
      }
      //记录日志表上传成功
      insertUploadLogSuccess(zipName, upLoadNo, "1");
    } catch (Exception e) {
      // 记入日志表
      insertUploadLogError(zipName, upLoadNo, e.toString(), "1");
      result.setResultCode("1");
      result.setResultMsg(e.toString());
    } finally {
      //删除本地目录,传目录路径
      UploadUtil
          .deletefile(localFilePath.substring(0, localFilePath.lastIndexOf(UploadUtil.xiegang)));
    }

    return JSONObject.toJSONString(result);
  }

  private void insertUploadLogError(String zipName, String upLoadNo, String errorData, String businessType) {
    CookUploadLog uploadLog = new CookUploadLog();
    uploadLog.setUpLogId(DateUtil.getFormatTimeString(new Date(), DateUtil.DATE_FORMATE_STRING_DEFAULT) + RandomUtil
        .getRandomNumString(4));
    uploadLog.setFileName(zipName);
    uploadLog.setUploadNo(upLoadNo);
    uploadLog.setUploadStatus("1");
    uploadLog.setBusinessType(businessType);
    if(errorData != null && errorData.length() > 180){
      errorData = errorData.substring(0, 180);
    }
    uploadLog.setRemark("upload error: " + errorData);
    goDao.insertUploadLog(uploadLog);
  }

  private void insertUploadLogSuccess(String zipName, String upLoadNo, String businessType) {

    CookUploadLog uploadLog = new CookUploadLog();
    uploadLog.setUpLogId(DateUtil.getFormatTimeString(new Date(), DateUtil.DATE_FORMATE_STRING_DEFAULT) + RandomUtil
        .getRandomNumString(4));
    uploadLog.setFileName(zipName);
    uploadLog.setUploadNo(upLoadNo);
    uploadLog.setUploadStatus("0");
    uploadLog.setBusinessType(businessType);
    uploadLog.setRemark("upload success");
    goDao.insertUploadLog(uploadLog);
  }

  private boolean checkUploadCooker(String uploadNo) {

    Map<String, Object> inParams = new HashMap<>();
    inParams.put("uploadNo", uploadNo);
    inParams.put("businessType", "1");
    inParams.put("uploadStatus", "0");
    int npUploadLogCount = goDao.selectNpUploadLogByUploadNoCount(inParams);

    if (npUploadLogCount > 0) {
      return true;
    }
    return false;

  }
}
